package com.my.mall.manage.imageInfo.controller;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.my.mall.common.R;
import com.my.mall.manage.imageInfo.dto.ImageInfoManageDTO;
import com.my.mall.manage.imageInfo.service.ImageInfoManageService;

@Controller
public class ImageInfoManageController {

	@Autowired
	ImageInfoManageService fileService;
	
	@Value("${img.path}")
	private String IMG_PATH;

	@RequestMapping("manage/upload")
	@ResponseBody
	public R uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request, int imgType) {

		String originalName = file.getOriginalFilename();

		String fileName = System.currentTimeMillis() + originalName.substring(originalName.lastIndexOf("."));

		String updatePath = IMG_PATH;

		if (!file.isEmpty()) {
			try {
				Path path = Paths.get(updatePath);
				if (!Files.exists(path))
					Files.createDirectories(path);
				Files.copy(file.getInputStream(), Paths.get(updatePath, fileName));
			} catch (IOException e) {
			//	log.error(e.toString(), e);
				return R.error("系统错误" + e.toString());
			}
		}

		return saveImg(originalName, imgType, "upload/" + fileName);
		// return saveFile(originalName, filePath);

	}

	public R saveImg(String name, int imgType, String imgUrl) {
		ImageInfoManageDTO file = new ImageInfoManageDTO();
		file.setName(name);
		file.setImgUrl(imgUrl);
		file.setImgType(imgType);
		file.setCreateTime(new Date());
		fileService.saveImg(file);
		return R.ok().put("file", file);
	}

}
